<?php
// +----------------------------------------------------------------------
// | 随访系统
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2050 http://www.hedesoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +---------------------------------------------------------------------
// | Author: 小李子 < 490959289@qq.com>
// +----------------------------------------------------------------------
namespace app\common\model;

use think\Model;
use think\Db;
class AdminUser extends Model
{
    public function admingroups()
    {
        return $this->belongsToMany('AdminGroup','AdminUserGroup','w_group_id','w_admin_id');
    }
    /**
     * 检查账号密码
     * @param $login_name 登录名称
     * @param $login_pwd 登录密码
     * @access public
     */
	public function login($login_name,$login_pwd)
	{
		$user = $this->where('admin_name',$login_name)->whereOr('realname',$login_name)->whereOr('mobile',$login_name)->find();
		$login_pwd = md5($login_pwd);
		if (!$user){
			return ['status'=>0,'msg'=>'账号不存在'];
		}
		if ($user['admin_password']!=$login_pwd){
			return ['status'=>0,'msg'=>'登录密码错误'];
		}
		if ($user['is_del']==1){
			return ['status'=>0,'msg'=>'账号已被移除'];
		}
		return $this->loginToken($user['admin_id']);
	}
	/**
     * 登录及缓存
     * @param $login_name 登录名称
     * @param $login_pwd 登录密码
     * @access private
     */
	public function loginToken($uid)
	{
		$user = $this->where('admin_id',$uid)->find();
		$code = mt_rand();
		$token = md5(time().md5($code));
		cache('token_'.$token, $user);
		$token_data = [
    		'uid'=>$uid,
    		'token'=>$token,
    		'ctime'=>time(),
    	];
    	$run = Db::name('user_token')->insert($token_data);
    	if ($run){
    		return ['status'=>1,'msg'=>'登录成功','token'=>$token];
    	}else{
    		return ['status'=>0,'msg'=>'token生成失败'];
    	}
		
	}
}